<?php
class trackController extends AController {
	// 回访跟进
	public function indexAction() {
		$page = $this->request->getGetParameter('p', 1);
		$pageSize = 10;
		
		$startTime = $this->request->getGetParameter('startTime');
		$endTime = $this->request->getGetParameter('endTime');
		$selDep = $this->request->getGetParameter('selDep');
		$this->selDep = $selDep;
		ATools::addSquote($selDep);
		$selStatus = $this->request->getGetParameter('selStatus');
		ATools::addSquote($selStatus);
		$doc = $this->request->getGetParameter('doc');
		
		$where = '1=1'.($startTime ? " AND VT.CREATE_TIME>='{$startTime}'" : '')
		.($endTime ? " AND VT.CREATE_TIME<='{$endTime}'" : '')
		.($doc ? " AND ZY.ZYDOC LIKE '%{$doc}%'" : '')
		.(count($selDep) > 0 ? " AND ZY.CY_DEP_NO IN (".implode(',', $selDep).")" : '')
		.(count($selStatus) > 0 ?
				(in_array('A', $selStatus)?  " AND (V.VISIT_STATE IN (".implode(',', $selStatus).") OR
						V.VISIT_STATE IS NULL)" : (" AND V.VISIT_STATE IN (".implode(',', $selStatus).")")) : '');
		
		$fields = "P.PATIENT_ID, P.TRUE_NAME, P.PHONE, P.SEX, P.BIRTH, ZY.RY_DATE, ZY.CY_DATE, ZY.CY_DEP, ZY.ZYDOC, ZY_AGE, ZY.BIZ_CODE,
		CASE
		WHEN COUNT(1) > 1 THEN to_char(COUNT(1))
		ELSE V.VISIT_STATE
		END AS VISIT_STATE,
		max(V.VISIT_TIME) as LAST_VISIT_TIME,
		V.VISIT_STATE AS LAST_VISIT_STATE";
		
		$sql = "SELECT {$fields} FROM ZHUYUAN ZY
		LEFT JOIN PATIENT P ON ZY.REF_PATIENT_ID=P.PATIENT_ID
		LEFT JOIN VISIT V ON 'ZY_'||ZY.ZY_NO||'_'||ZY_TIMES=V.BIZ_CODE
		WHERE {$where}
		GROUP BY P.PATIENT_ID, P.TRUE_NAME, P.PHONE, P.BIRTH, P.SEX, ZY.RY_DATE, ZY.CY_DATE, ZY.CY_DEP, ZY.ZYDOC, ZY_AGE, ZY.BIZ_CODE, ZY.ZY_CODE,VISIT_STATE
		ORDER BY ZY.ZY_CODE";
		
		// TODO 暂时采用本方法获取下一位信息
		$visitSql['where'] = $where;
		$visitSql['fields'] = $fields;
		$visitSql['orderField'] = 'ZY.ZY_CODE';
		$visitSql['orderType'] = 'ASC';
		$_SESSION['visitZySql'] = $visitSql;
		
		$totalCount = 0;
		$this->startNum = ($page - 1) * $pageSize + 1;
		$this->rows = JYDB::query($sql, $page, $pageSize, $totalCount);
		$this->pager = JYTools::pager('index.php?c=visitzy&a=index&p=_num_', $totalCount, $page);
		$this->startTime = $startTime;
		$this->endTime = $endTime;
		$this->depts = JYDep::getZyDepts(CSM_UNIT_ID);
		$this->selStatus = $selStatus;
		return $this->render();
	}
	
	// 跟进回访
	public function formAction() {
		
	}
}